package com.millstein.springcloud.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.millstein.springcloud.entities.CommonResult;
import com.millstein.springcloud.entities.Payment;
import com.millstein.springcloud.service.PaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class CircleBreakerController {

    public static final String SERVICE_URL = "http://nacos-payment-provider";

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/consumer/fallback/{id}")
    /* 情况1：不进行任何配置 */
    // @SentinelResource(value = "fallback")
    /* 情况2：只配置fallback */
    // @SentinelResource(value = "fallback", fallback = "handlerFallback")
    /* 情况3：只配置blockHandler */
    // @SentinelResource(value = "fallback", blockHandler = "handlerBlockHandler")
    /* 情况4：同时配置fallback和blockHandler */
    @SentinelResource(value = "fallback", fallback = "handlerFallback", blockHandler = "handlerBlockHandler")
    public CommonResult<Payment> fallback(@PathVariable Long id) {
        CommonResult<Payment> result = restTemplate.getForObject(SERVICE_URL + "/paymentSQL/" + id,
                CommonResult.class, id);
        if (id == 4) {
            throw new IllegalArgumentException("IllegalArgumentException, 非法参数异常。。。");
        } else if (result.getData() == null) {
            throw new NullPointerException("NullPointerException, 该ID没有对应的记录，空指针异常");
        }
        return result;
    }

    public CommonResult handlerFallback(Long id, Throwable e) {
        Payment payment = new Payment(id, null);
        return new CommonResult(444, "兜底异常类handlerFallback被触发！原因是" + e.getMessage(), payment);
    }

    public CommonResult blockHandler(Long id, BlockException e) {
        Payment payment = new Payment(id, null);
        return new CommonResult(445, "兜底异常类handler-sentinel被限流！原因是" + e.getMessage(), payment);
    }

    // ==================openfeign
    @Autowired
    private PaymentService paymentService;

    @GetMapping("/consumer/feign/{id}")
    public CommonResult<Payment> paymentSQL(@PathVariable("id") Long id) {
        return paymentService.paymentSQL(id);
    }

}
